//
//  ZYTabBar.swift
//  ZYweibo
//
//  Created by 张耀 on 16/6/25.
//  Copyright © 2016年 zhangyao. All rights reserved.
//

import UIKit

    //声明协议
protocol ZYTabBarDelegate: NSObjectProtocol{
    //声明协议方法
    func jiahaoButtonClick()

}

class ZYTabBar: UITabBar {
    
    //使用weak 修饰代理需要继承NSObjectProtocol 基本协议
    weak var zyDelegate:ZYTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        shitu()
    }
    
    //监听方法
   @objc private func buttonClick(){
    
        zyDelegate?.jiahaoButtonClick()
    
    }
    
    //设置加号按钮
    private lazy var jiahaoButton: UIButton = {
    
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
    
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.sizeToFit()
    
        return button
    }()

    //设置按钮的frame
    
    override func layoutSubviews() {
        
        jiahaoButton.center.x = self.frame.width * 0.5
        jiahaoButton.center.y = self.frame.height * 0.5
        
        //设置UITabBarButton的宽
        let width = KUAN  / 5
        
        //记录标识
        var index: CGFloat = 0
        
        //通过遍历其类身上的子控件
        
        for anniu in self.subviews{
        
            //判断其是
            if anniu.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                //设置宽
                anniu.frame.size.width = width
                
                //设置X
                anniu.frame.origin.x = index * width
            
                index++
                
                //给加号按钮留距离
                if index == 2{
                
                    index++
                }
            }
        }
    }
    
    //设置视图
    
    func shitu(){
        
        addSubview(jiahaoButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
